<template>
	<view style="height: 100vh;overflow: hidden;">
		<view :style="'padding-top:' + (navTop * 2 - 6) + 'rpx;'" class="pots">
			<view class="top-title">工厂地图</view>
		</view>
		<view class="df ac sb" :style="'padding-top:' + (navTop * 2 - 6 + 90) + 'rpx;'">
			<view class="" style="flex:1">
				<van-search :field-class="'height:80rpx'" :value="value" placeholder="请输入关键词搜索" @change="changVal"
					shape="round" @search="goSearch" />
			</view>
			<view class="mr10 change-map" style="position: relative;" @click="goFactoryMap(1)">
				<view class="f12">
					切换地图模式
				</view>
				<view class="label_icon" v-if="showLabel" @click="showLabel = false">
					<image style="width:260rpx;max-height:70rpx"
						:src="getImgSrc('/uploads/20241119/1731989938673c11b270afb.png')" mode="widthFix" />
				</view>
			</view>
		</view>
		<view style='position: relative;z-index: 9999;'>
			<add-tips :text="'下次找工厂更方便'"/>
		</view>
		<view class="post" :style="'top:' + (navTop * 2 + 82) + 'rpx;'" style="z-index: 100;">
			<ul class="df ac bgcf bbf1">
				<block v-for="(item, index) in tab_list" :key="index">
					<li class="df ac jc  w50" @tap.native="ontabShow(index)" :data-i="index"
						style="width: 250rpx;height:72rpx">
						<P :class="'f14 ' + (item.show ? 'c10' : 'c6b')" class="tabListName">{{ item.name }}</P>
						<image class="down ml8" referrerPolicy='no-referrer'
							:src="item.show ? 'https://wx.xtwaixie.com/img/down1.png' : 'https://wx.xtwaixie.com/img/down.png'" />
					</li>
				</block>
			</ul>
		</view>
		<view style="padding:0rpx 0rpx">
			<view v-if="!isAuth_location">
				<AuthorizeMap @emitAuth="emitAuth" />
			</view>
			<view class="" v-else style="position: relative;">
				<view style="position: relative;" v-show="expand">
					<map id="map" style="width:100%;height:280rpx;" :longitude="longitude" :latitude="latitude"
						:scale="map_scale" :controls="controls" :zIndex="true" @markertap="markertap" @callouttap="markertap"
						:markers="markers" show-location>
						<!--  v-if="!is_simple"@regionchange="regionchange" -->
						<cover-view slot="callout">
							<cover-view v-for="(item,index) in markers" :marker-id="item.id" :key="index"
								:style="'position: relative;z-index:'+ item.zIndex">
								<cover-view
								:style="'position: relative;z-index:'+item.zIndex"
									:class="detail.id == item.id ? 'customCallout_active customCallout' : 'customCallout'"
									:key="index" :marker-id="item.id" v-show="item.showLabel">
									<cover-view
										:class="detail.id == item.id? 'marker-box-text-active marker-box-text f13' : 'marker-box-text f13'"
										style="margin-bottom:15rpx;">
										<cover-view class="van-ellipsis"
											style="width:100%;height:100%;line-height: 50rpx;">
											{{item.options.labelName}}
										</cover-view>
									</cover-view>
								</cover-view>
							</cover-view>
						</cover-view>
					</map>
					<view style="position:absolute;right:20rpx;top:20rpx;" @click="changeExpand(false)">
						<van-icon name="clear" size="46rpx" color="#00000070" />
					</view>
					<view class="look_big_map" @click="goFactoryMap(0)">
						<view class="df ac" style="margin-right:6rpx">
							<image class="img16" src="https://wx.xtwaixie.com/img/expand.png" />
						</view>
						进入地图
					</view>
				</view>
				<view style="height:40rpx" class="expandMapButton" @click="changeExpand(true)" v-show="!expand">展开小地图
					<view class="expandMapImg">
						<image src="https://wx.xtwaixie.com/img/expandMapButton.png" />
					</view>
				</view>
			</view>
		</view>
		<view v-if="isAuth_location" class="listContainer" style="position: relative;" :style="{boxShadow: !expand ? '0 3rpx 15rpx 2rpx gray' : ''}">
			<view class="fixed-view" :style="expand ? 'top:-150rpx;' : '-50rpx;'" ref="fixedView">
			</view>
			<scroll-view ref="listContainer" :scroll-into-view="'#'+ detail.id"
				:style="'height:calc(100vh - '+scrollHeight+'rpx)'" scroll-y @scrolltolower="loadNext()"
				:scroll-top="scrollTop" @scroll="onScroll" class="" v-if="markers.length != 0">
				<view class="factory_box bgcf "
					:class="(detail.id == item.id ||highlightedIndex == index) && expand? `factory_border item${index}` : `item${index}`"
					v-for="(item,index) in markers" :key="index" :ref="'item' + index"
					@click="goPage('/subPack/factoryDetails/factoryDetails', item.uid)"
					:style=" 'margin-bottom:' + 0 + 'rpx' " :id="'#'+item.id">
					<!-- highlight_first &&  -->
					<view class="df ac sb">
						<view
							:class="item.doorboard != '' && item.doorboard ? 'factory_img' : 'factory_img df ac jc fc'">
							<view class="" style="width: 100%;height:100%;"
								v-if="item.doorboard != '' && item.doorboard">
								<image :src="getImgSrc(item.doorboard)" mode="aspectFill">
								</image>
								<view class=""
									style="position: absolute;left: 10rpx;top: 10rpx;width: 100rpx;height: 36rpx;">
									<image
										style="position: absolute;left: 0rpx;top: 1rpx;width: 100rpx;border-radius: 0rpx;"
										src="@/static/icon/rzns_icon.png" mode="widthFix"></image>
									<view class="factory_year">
										入驻{{ item.year }}年
									</view>
								</view>
							</view>
							<view class="" v-else>
								<view class="df jc">
									<image style="width:80rpx;"
										:src="getImgSrc('/uploads/20241023/17296638126718934463b45.png')"
										mode="widthFix"></image>
								</view>
								<view class="mt10" style="color:#BBBBBB;">
									未上传形象照
								</view>
							</view>
						</view>
						<view class="factory_content">
							<h2 class="f16 c28 f600 mt5 factory_title" style="font-size: 32rpx;">{{ item.company }}</h2>
							<view class="df ac mt5" style="width: 100%;">
								<view class="df ac mr5" :style="isIndex ? 'margin-right:10rpx;' : 'margin-right:2rpx;'"
									v-if="item.latitude != '0' && item.longitude != '0'">
									<view class="df ac " style="transform: translateY(3rpx);">
										<uni-icons type="location" color="#1050c7"
											:size="isIndex ? 20 : 22"></uni-icons>
										<!-- <image style="width: 30rpx;" src="../../static/ditubiao.png" mode="widthFix"></image> -->
									</view>
									<view :class="isIndex ? 'f13 c10' : 'f12 c10'">
										距您{{ item.distance_in_km}}{{item.unit}}
									</view>
								</view>
								<!-- 至尊会员 -->
								<view class="df ac mr5" v-if="item.grade === 2 && item.grade_type === 1">
									<image :style=" isIndex ? 'height: 38rpx;' : 'height: 35rpx;'"
										:src="getImgSrc('/uploads/20250228/174070970167c11f451f7ad.png')" mode="heightFix">
									</image>
								</view>
								<!-- 基础会员 -->
								<view class="df ac mr5" v-if="item.grade === 2 && item.grade_type === 0">
									<image :style=" isIndex ? 'height: 38rpx;' : 'height: 35rpx;'"
										:src="getImgSrc('/uploads/20250228/174070968667c11f3636140.png')" mode="heightFix">
									</image>
								</view>
								<view class="df ac" v-if="item.state === 1">
									<image :style=" isIndex ? 'height: 52rpx;' : 'height: 48rpx;' "
										src="@/static/icon/gsrz_icon.png" mode="heightFix">
									</image>
								</view>
							</view>
							<view class="df ac mt5" style="width: 100%;">
								<view class="factory_content_name f14">工艺：</view>
								<view class="factory_content_text f14">
									{{ item.machining ? item.machining : '--' }}
								</view>
							</view>
							<view class="df ac mt5" style="width: 100%;">
								<view class="factory_content_name f14">行业：</view>
								<view class="factory_content_text f14">
									{{ item.service_industry ? item.service_industry : '--'}}
								</view>
							</view>
							<view class="mt5 f14"
								style="width: 100%;color:gray;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;display:flex;align-items:center;justify-content:center">
								<view style="display:flex;flex-direction: column;width:50%;text-align:center;border-right:1px solid #D1D1D1">
									<view>员工数：</view>
									<view>{{ item.staff ? item.staff : '--' }}</view>
								</view>
								<view style="display:flex;flex-direction: column;width:50%;text-align:center">
									<view>工厂面积：</view>
									<view>{{ item.factory_area ? item.factory_area : '--'}}</view>
								</view>
							</view>
						</view>
					</view>
					<view class="factory_img_box df mt10"
						v-if="item.machining_products && item.machining_products.length != 0">
						<view class="factory_img_item" style="margin-right: 22rpx;"
							v-for="(product,idx) in item.machining_products.slice(0,4)" :key="idx">
							<image v-if="checkType(product.url)" :src="getImgSrc(product.url[0])" mode="aspectFill">
							</image>
							<image v-else :src="getImgSrc(product.url)" mode="aspectFill">
							</image>
						</view>
					</view>
					<view class="highlight-card" v-show="highlightedIndex == index && expand">
						<view class="highlight-box"></view>
						<image :src="getImgSrc('/uploads/20240925/172723812766f38fef41cdd.png')" mode="aspectFill">
						</image>
					</view>
					<view class="factory-hairline--bottom" v-show="!expand"></view>
					<view style="height:20rpx;width:100%" v-show="expand"></view>
				</view>
				<view class="" v-show="loading" style="display:flex;justify-content: center;padding:6rpx 0">
					<van-loading v-show="loading" size="48rpx">加载中...</van-loading>
				</view>
				<view class="Not satisfied mt20" v-if="is_lookAfter">
					<view class="f14" style="color:#1050c7;text-align:center;">
						<view v-if="!token">登录后可查看全部工厂</view>
						<view v-if="cg_status == 0 && token">非注册采购商仅展示10家工厂，注册后展示更多工厂</view>
						<view v-else-if="cg_status == 1 && token">审核中的采购商仅展示10家工厂，审核成功后展示更多工厂</view>
						<view v-else-if="cg_status == 3 && token">被驳回的采购商仅展示10家工厂，审核成功后展示更多工厂</view>
						
					</view>
					<view v-if="!token" class="free_join_in" @click="goPage('/pages/login/login')">
						登录
					</view>
					<view v-if="cg_status == 0 && token" class="free_join_in" @click="goPage('/pages/my/editInfo')">
						免费注册
					</view>
					<view v-else-if="cg_status == 1 && token" class="free_join_in" @click="goPage('/pages/my/editInfo')">
						前往查看
					</view>
					<view v-else-if="cg_status == 3 && token" class="free_join_in" @click="goPage('/pages/my/editInfo')">
						重新填写
					</view>
					<view style="height: 60rpx;"></view>
				</view>
				
			</scroll-view>
			<p class="db tc mt40 f14 c9" v-else>没有找到任何内容~</p>
		</view>
		<view style="height: 150rpx;"></view>
		<tabbar></tabbar>

		<van-popup :show="screen_popup" @close="closePopup" position="top">
			<view class="" :style="'padding-top:' + (navTop * 2 + 90) + 'rpx;'">
				<ul class="df ac bgcf bbf1">
					<block v-for="(item, index) in tab_list" :key="index">
						<li class="df ac jc h44 w50" @tap.native="ontabSel($event, { i: index })" :data-i="index"
							style="width: 250rpx;">
							<P :class="'f14 ' + (item.show ? 'c10' : 'c6b')" class="tabListName">{{ item.name }}</P>
							<image class="down ml8" referrerPolicy='no-referrer'
								:src="item.show ? 'https://wx.xtwaixie.com/img/down1.png' : 'https://wx.xtwaixie.com/img/down.png'" />
						</li>
					</block>
				</ul>
				<view class="" style="display: flex;" v-if="tab_list[0].show">
					<view class="position_screen">
						<view class="mt10">
							当前位置
						</view>
						<view class="position_list df mt20">
							<view
								:class="screen_index[0] == index ? 'position_item_active position_item' : 'position_item'"
								:style="index == 0 ? '' : 'line-height:65rpx'" @click="changeScreen(0,index)"
								v-for="(item,index) in position_screen" :key="index">
								<view class="">
									{{ item === 0 ? '附近' : item + '公里' }}
								</view>
								<view class="f12" v-if="item === 0"
									:style=" screen_index[0] == index ? 'color:#4874CB;' : 'color:gray'">
									智能范围
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="h360" style="display: flex;" v-if="tab_list[1].show">
					<scroll-view class="h360 bgcf7" :scroll-y="true" style="width: 250rpx;">
						<ul class="db">
							<block v-for="(item, index) in info.machiningre" :key="index">
								<li class="pd015 h48 df ac sb" :class="{bgcf:screen_index[1] == index}"
									@tap.native="changeTab(index,item.id,item.name)">
									<p :class="'f14 c28 ' + (screen_index[1] == index ? 'c10' : '')">{{ item.name }}
									</p>
								</li>
							</block>
						</ul>
					</scroll-view>
				</view>
				<view class="df" v-if="tab_list[2].show">
					<scroll-view class="h360 w125 bgcf7" :scroll-y="true">
						<ul class="db">
							<block v-for="(item, index) in province_list" :key="index">
								<li :class="'tab-left ' + (region[0].act === item.region_id ? 'bgcf' : '')"
									@tap.native="onRegion($event, { name: item.region_name, id: item.region_id, type: 0 })"
									:data-name="item.region_name" :data-id="item.region_id" :data-type="0">
									<p :class="'f14 c28 ovh w110 ' + (region[0].act === item.region_id ? 'c10' : '')">
										{{ item.region_name }}
									</p>
								</li>
							</block>
						</ul>
					</scroll-view>
					<scroll-view class="h360 f1" :scroll-y="true">
						<ul class="db">
							<block v-for="(item, index) in city_list" :key="index">
								<li class="pd015 h48 df ac sb"
									@tap.native="onRegion($event, { name: item.region_name, id: item.region_id, type: 1 })"
									:data-name="item.region_name" :data-id="item.region_id" :data-type="1">
									<p :class="'f14 c28 ' + (region[1].act === item.region_id ? 'c10' : '')">
										{{ item.region_name }}
									</p>
									<image class="sel" src="https://wx.xtwaixie.com/img/sel.png"
										v-if="region[1].act === item.region_id" />
								</li>
							</block>
						</ul>
					</scroll-view>
				</view>
			</view>
		</van-popup>
	</view>
</template>

<script>
	import tabbar from '@/component/tabbar/tabbar';
	import top from '@/component/top/top';
	const app = getApp();
	import http from '../../utils/http';
	import AuthorizeMap from '@/component/authorize-map/authorize-map'
	import FactoryInfo from '@/component/factory'
	import addTips from '@/component/addTips';
	let debounceTimeout;
	export default {
		components: {
			tabbar,
			top,
			AuthorizeMap,
			FactoryInfo,
			addTips
		},
		computed: {
			scrollHeight() {
				if (this.expand) {
					return 190 + 80 + 280 + 220
				} else {
					return 190 + 80 + 40 + 220
				}
			}
		},
		data() {
			return {
				scrollTop:0,
				scrollViewTop:0,
				expand: true, //地图展开
				detail: {
					id: ""
				},
				highlight_first: true,
				loading: false,
				is_simple: false,
				navTop: '',
				value: '',
				page: 1,
				screen_popup: false,
				position_screen: [0, 5, 20, 50, 100],
				screen_index: [-1, 0, -1],
				tab_list: [{
						show: false,
						name: '距离',
						act: ''
					},
					{
						show: false,
						name: '工艺',
						act: ''
					},
					{
						show: false,
						name: '地区',
						act: '',
					}
				],
				province_list: [],
				city_list: [],
				polylinePoints: [{
						longitude: 120.54321,
						latitude: 30.09876
					},
					{
						longitude: 120.65432,
						latitude: 30.18765
					},
					{
						longitude: 120.76543,
						latitude: 30.27654
					}
				],
				map_scale: 17,
				longitude: 0,
				latitude: 0,
				my_longitude: 0,
				my_latitude: 0,
				controls: [{
					id: 1,
					// iconPath: 'https://cdn.xtwaixie.com/uploads/20240925/172723812766f38fef41cdd.png',
					// position: {
					// 	left: 0,
					// 	top: 300 - 50,
					// 	width: 50,
					// 	height: 50
					// },
					clickable: true
				}],
				markers: [],
				isAuth_location: false,
				info: [],
				region: [{
					name: '',
					act: ''
				}, {
					name: '',
					act: ''
				}, {
					name: '',
					act: ''
				}],
				province: '',
				city: '',
				url: '/pages/editSettled/editSettled',
				not_join: false,
				showJoin: true,
				list: [],
				pageTotal: 0,
				showLabel: true,
				is_lookAfter: false,
				user_info: null,
				highlightedIndex: 0,
				mapContext:null,
				is_scroll:false,
				cg_status:0,
				token: '',
			};
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		mounted() {
			const mapContext = uni.createMapContext('map', this);
			this.mapContext = mapContext;
			// console.log(this.mapContext)
		},
		onLoad(options) {
			
			this.setData({
				navTop: app.globalData.navTop
			});
			this.getBase();
			this.getArea(1);
			setTimeout(() => {
				this.showLabel = false
			}, 5000)

			this.list = []
			this.getAllInfo()
			// this.wxAuthLogin();
			let token = uni.getStorageSync('token');
			if (token) {
				this.token = token
				this.getInfo();
				this.getUserInfo()
				// this.getList()
				
			}
			const that = this
			
			uni.getSetting({
				success(res) {
					that.isAuth_location = res.authSetting['scope.userLocation']
				}
			})
			
			// console.log(this.markers)
			
		},
		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady() {},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow() {
			this.checkAuth()
			setTimeout(()=>{
				this.getScrollViewTop()
			},1500)
			// this.list = []
			// this.getAllInfo()
			// this.wxAuthLogin();
			// let token = uni.getStorageSync('token');
			// if (token) {
			// 	this.getInfo();
			// 	// this.getList()
			// }
			// const that = this
			// uni.getSetting({
			// 	success(res){
			// 		that.isAuth_location = res.authSetting['scope.userLocation']
			// 	}
			// })
			let token = uni.getStorageSync('token');
			if (token) {
				this.token = token
				this.getInfo();
				this.getUserInfo()
				// this.getList()
				
			}
		},
		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide() {},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload() {},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh() {},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom() {
			// 判断工厂是否只显示10个
			if (this.page < this.pageTotal) {
				if (!uni.getStorageSync('token') || this.cg_status !=2 && this.page == 1 ) {
					console.log(1)
					this.is_lookAfter = true
					return
				}
				
					
					
				// 	return
				// }
				if (this.user_info && this.user_info.grade == 0 && this.page == 1) {
					this.is_lookAfter = true
					this.loading = false
					console.log(this.is_lookAfter, this.loading)
					return
				}
				this.page++
				this.getList()
			} else {
				uni.showToast({
					title: '没有更多了~',
					icon: 'none'
				});
			}
			// this.loadNext()
		},
		watch: {
			map_scale(nval) {
				this.map_scale_watch = nval
			},
			map_scale_watch(nval) {
				console.log(nval)
				if (nval <= 8) {
					this.markers.forEach((item, index) => {
						const is_svip =  item.grade === 2 && item.grade_type === 1
						const is_show = this.tab_list[0].act != '' && this.tab_list[0].act >= 100 ? is_svip : true
						if (item.id == this.detail.id || is_show) {
							item.width = item.id == this.detail.id ? 35 : 25
							item.height = item.id == this.detail.id ? 35 : 25
							item.iconPath = item.id == this.detail.id ? this.current_map_icon : this.map_icon
							item.showLabel = true
						} else {
							item.width = 25
							item.height = 25
							item.iconPath = this.map_icon
							item.showLabel = false
						}
					})
				} else {
					this.markers.forEach((item, index) => {
						const is_svip =  item.grade === 2 && item.grade_type === 1
						const is_show = this.tab_list[0].act != '' && this.tab_list[0].act >= 100 ? is_svip : true
						if (item.id == this.detail.id) {
							item.width = 35
							item.height = 35
							item.iconPath = this.current_map_icon
							item.showLabel = true
						} else {
							item.width = 25
							item.height = 25
							item.iconPath = this.map_icon
							item.showLabel = is_show
						}
					})
				}
			}
		},

		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage() {},
		methods: {
			changeExpand(value) {
				this.expand = value
			},
			getScrollViewTop(){
				const query = uni.createSelectorQuery().in(this);
				query.select(`.item0`).boundingClientRect((data) => {
					
					if(data){
						this.scrollViewTop = data.top
					} else {
						this.scrollViewTop = 366
					}
				}).exec();
			},
			markertap(e) {
				// console.log(e)
				const markerId = e.detail.markerId
				let index = this.markers.findIndex(item => item.id == markerId)
				this.setMapDetail(markerId)
				const query = uni.createSelectorQuery().in(this);
				this.scrollTop = 0
				
				this.page = 1
				this.latitude = this.markers[index].latitude
				this.longitude = this.markers[index].longitude
				
				this.getList()
				setTimeout(()=>{
					this.markers = []
				},50)
				// setTimeout(()=>{
				// 	this.is_scroll = true
					
				// 	query.select(`.item${this.highlightedIndex}`).boundingClientRect((data) => {
				// 		console.log(data,this.scrollViewTop)
				// 		this.scrollTop = data.top - this.scrollViewTop
				// 		// console.log(this.scrollTop,'this.scrollTop ' ,2331.421875)
				// 	}).exec();
				// 	setTimeout(()=>{
				// 		this.is_scroll = false
				// 	},1500)
				// },100)
			},
			setMapDetail(id) {
				let index = this.markers.findIndex(item => item.id == id)
				if (index == -1) return
				
				this.highlightedIndex = index;
				let list = this.markers.filter(item => item.width == 40)
				list.forEach((item, index1) => {
					item.iconPath = this.getImgSrc(
						'/uploads/20240925/172723812766f38fef41cdd.png')
					item.width = 30
					item.height = 30
					item.zIndex = 9
				})
				this.markers[index].width = 40
				this.markers[index].height = 40
				this.markers[index].iconPath = this.getImgSrc(
					'/uploads/20241023/172966259367188e81d9230.png'
				)
				this.markers[index].showLabel = true
				this.markers[index].zIndex = 999
				this.detail = this.markers[index]
			},
			onScroll() {
				clearTimeout(debounceTimeout);
				// if(!this.expand){
				// 	this.highlightedIndex = 0;
				// 	return
				// }
				
				if(this.is_scroll){
					return
				}
				debounceTimeout = setTimeout(() => {
					
					const query = uni.createSelectorQuery().in(this);
					let fixedView = null;
					let halfViewHeight = 0;

					query.select(".fixed-view").boundingClientRect((data) => {
						fixedView = data;
						halfViewHeight = data.height;
					}).exec();
					
					setTimeout(() => {
						if (halfViewHeight != 0) {
							console.log('onScroll触发')
							// this.map_scale = 8
							this.markers.forEach((it, index) => {
								const item = query.select(`.item${index}`)
								if (item) {
									item.boundingClientRect((itemPosition) => {
										if (itemPosition.top < fixedView.bottom &&
											itemPosition.bottom >= fixedView.top +
											halfViewHeight) {

											if (this.highlightedIndex !== index) {
												this.highlightedIndex = index;
												this.setMapDetail(it.id)

												this.moveMarkerToCenter({
													latitude: it.latitude && it.latitude != 0 ? it.latitude : this.my_latitude,
													longitude: it.longitude && it.longitude != 0 ? it.longitude : this.my_longitude
												})
											}
										} else {
											it.width = 30
											it.height = 30
											it.iconPath = this.getImgSrc(
												'/uploads/20240925/172723812766f38fef41cdd.png'
											)
										}

									}).exec();
								} else {
									it.width = 30
									it.height = 30
									it.iconPath = this.getImgSrc(
										'/uploads/20240925/172723812766f38fef41cdd.png')
								}
							});
						}
					}, 100)
				}, 200);
			},
			loadNext() {
				if (this.page < this.pageTotal) {
					
					// 判断工厂是否只显示10个
					if (!uni.getStorageSync('token') || this.cg_status !=2  && this.page == 1) {
						this.is_lookAfter = true
						return
					}
					
					// console.log(this.is_lookAfter)
					if (this.user_info && this.user_info.grade == 0 && this.page == 1) {
						this.is_lookAfter = true
						this.loading = false
						return
					}
					this.page++
					this.getList()
					
				} else {
					uni.showToast({
						title: '没有更多了~',
						icon: 'none'
					});
				}
				
			},
			emitAuth(value) {
				this.isAuth_location = value
				if (this.isAuth_location) {
					this.getAllInfo()
				}
			},
			getUserInfo() {
				http.request('user/userInfo').then((res) => {
					this.user_info = res.data.userInfo
					res.data.userInfo.grade === 0 ? this.not_join = true : this.not_join = false
					// uni.setStorageSync('is_info', res.data.is_info);
					
					// 判断用户状态（注册信息状态）
					this.cg_status = this.user_info.cg_status
					
					if (!res.data.userInfo.settledStatus) {
						this.url = '/pages/editSettled/editSettled'
					} else {
						this.url = '/pages/Factoryinformation/Factoryinformation'
					}
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
				});
			},
			async getAllInfo() {
				const that = this
				try {
					const res = await uni.getSetting();
					that.isAuth_location = res[1].authSetting['scope.userLocation'];

					if (!this.isAuth_location) return; // 提前返回，如果未授权  
					const lat = uni.getStorageSync('latitude');
					const long = uni.getStorageSync('longitude');
					const address_component = uni.getStorageSync('address_component');
					// 如果已有坐标信息  
					if (lat && long) {
						this.latitude = lat;
						this.longitude = long;
						this.my_latitude = lat;
						this.my_longitude = long;
						if (address_component) {
							this.handleAddressComponent(JSON.parse(address_component));
						} else {
							const result = await this.getAreas(lat, long);
							this.handleAddressComponent(result.data.result.address_component);
						}
					} else {
						
						const location = await this.getLocation();
						this.latitude = location.latitude;
						this.longitude = location.longitude;
						uni.setStorageSync('latitude', this.latitude)
						uni.setStorageSync('longitude', this.longitude)
						this.my_latitude = location.latitude;
						this.my_longitude = location.longitude;
						const result = await this.getAreas(this.latitude, this.longitude);
						this.handleAddressComponent(result.data.result.address_component);
					
					}
				} catch (error) {}
			},
			handleAddressComponent(addressComponent) {
				const {
					province,
					city
				} = addressComponent;
				this.province = province;
				this.city = city;
				
				return this.getList();
			},
			changVal(e) {
				this.value = e.detail
			},
			ontabShow(index) {
				this.screen_popup = true
				this.tab_list.forEach((item, i) => {
					item.act = (index === i) ? i : '';
					item.show = (index === i);
				});
			},
			getList(longitude, latitude) {
				// longitude ? 1 : 
				let params = {
					page: longitude ? 1 : this.page,
					pageSize: 10,
					longitude: longitude && longitude != "0" ? longitude : this.longitude,
					latitude: latitude && latitude != "0" ? latitude : this.latitude,
					my_longitude: this.my_longitude,
					my_latitude: this.my_latitude,
					keyword: this.value,
					distance: this.tab_list[0].act ? this.tab_list[0].act : 0,
					machining: this.tab_list[1].act,
					service_industry: 0,
					province: longitude ? '' : this.region[0].name ? this.region[0].name : '',
					city: longitude ? '' : this.region[1].name ? this.region[1].name : '',
					type: 0
				}
				console.log(params,'params')
				if (longitude) {
					delete params.page
					delete params.pageSize
				}
				this.loading = true
				params.longitude = Number(params.longitude)
				params.latitude = Number(params.latitude)
				http.request('user_settled/list', params).then(res => {
					this.loading = false
					this.pageTotal = res.data.last_page
					res.data.data.forEach((item, index) => {
						item.machining = item.machining.join('、')
						item.service_industry = item.service_industry.join('、')
						
						item.machining_products.forEach(el=>{
							if (el.url.startsWith('[')) {  
							    try {  
							        el.url = JSON.parse(el.url);  
							    } catch (e) {  
							        el.url = null;
							    }  
							}  
						})
						item.unit = "公里"
						const distance = parseFloat(item.distance_in_km);
						if (isNaN(distance)) {
						    // console.error('Invalid distance value:', item.distance_in_km);
						    item.distance_in_km = 0;
						} else {
						    if (distance >= 100) {
						        item.distance_in_km = Math.floor(distance);
						    } else if (distance >= 1) {
						        item.distance_in_km = distance.toFixed(1);
						    } else {
						        item.distance_in_km = Math.floor(distance * 1000);
						        item.unit = "米";
						    }
						}
						const is_svip =  item.grade === 2 && item.grade_type === 1
						const is_show = this.tab_list[0].act != '' && this.tab_list[0].act >= 100 ? is_svip : true
						this.markers.push({
							...item,
							iconPath: this.getImgSrc('/uploads/20240925/172723812766f38fef41cdd.png'),
							width: 30,
							height: 30,
							current: false,
							options: {
								isStore: false,
								labelName: item.company.slice(0, 6) + '...',
								isSelect: index === 0 ? true : false
							},
							showLabel: is_show,
							customCallout: {
								anchorX: 0,
								anchorY: 0,
								display: "ALWAYS"
							},
							zIndex: 9
						})
						this.list.push({
							...item
						})
					})
					this.markers = this.markers.reduce((accumulator, current) => {
						if (!accumulator.find(marker => marker.id === current.id)) {  
							accumulator.push(current);  
						}  
						return accumulator;  
					}, []);
					if (this.markers.length > 0) {
						let scale = 0
						if (this.page == 1) {
							this.setMapDetail(this.markers[0].id)
							const min = this.markers[0];  
							const distance = min.distance_in_km;  
							
							if(min.unit == "公里"){
								if (distance >= 100) {
								    scale = 4.5;  
								} else if (distance >= 50) {  
								    scale = 5.5;  
								} else if (distance >= 40) {  
								    scale = 8;
								} else if (distance >= 20) {  
								    scale = 11; 
								} else if (distance >= 10) {  
								    scale = 10; 
								} else if (distance >= 5) {  
								    scale = 10;  
								} else if (distance >= 1) {  
								    scale = 9;
								} else {  
								    scale = 14;
								}  
							} else {
								scale = 14;
							}
							
							// console.log(scale)
							
							let totalLatitude = this.my_latitude;
							let totalLongitude = this.my_longitude;
							totalLatitude += Number(min.latitude);
							totalLongitude += Number(min.longitude);
							setTimeout(() => {
								if (scale != 0) {
									this.map_scale = scale
								}
							}, 500)
						}
					}
					uni.hideLoading()
				}).catch(err => {
					uni.showToast({
						title: err,
						icon: 'none'
					})
					uni.hideLoading()
				})
			},
			moveMarkerToCenter(marker) {
				this.longitude = 0
				this.latitude = 0
				setTimeout(() => {
					this.longitude = marker.longitude;
					this.latitude = marker.latitude;
					this.map_scale = 17;
				}, 10)

			},
			closePopup() {
				this.screen_popup = false
				this.tab_list.forEach((item, i) => {
					// item.act = '';
					item.show = false;
				});
			},
			getArea(id) {
				const data = {
					pid: id
				};
				http.request('base/region', data).then((res) => {
					if (id === 1) {
						this.setData({
							province_list: res.data
						});
					} else {
						this.setData({
							city_list: res.data
						});
					}
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
				});
			},
			getBase() {
				http.request('base/configData').then((res) => {
					const machiningData = res.data.machining || [];
					res.data.machiningre = [{
						id: 0,
						name: '全部',
						children: []
					}, ...machiningData];
					res.data.machiningre.forEach(item => {
						item.children.unshift({
							name: "全部",
							id: item.id,
							machining_type: 0
						});
					});
					this.info = res.data
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
				});
			},
			regionchange(e) {
				let {
					scale,
					type,
					causedBy,
					centerLocation
				} = e.detail;
				console.log(e.detail, scale)
				if (type === 'end') {
					this.is_simple = false;
					this.getList(centerLocation.longitude, centerLocation.latitude)
				}
			},
			changeScreen(i, index) {
				if (this.screen_index[i] === index) {
					this.$set(this.screen_index, i, -1);
				} else {
					this.$set(this.screen_index, i, index);
				}
				const name = this.position_screen[index]
				this.setData({
					[`tab_list[${i}].show`]: false,
					[`tab_list[${i}].name`]: name === 0 ? '附近' : name + '公里',
					[`tab_list[${i}].act`]: name,
					page: 1,
					list: [],
					markers: [],
					highlightedIndex:0
				})
				this.screen_popup = false
				this.getIp(11,name)
				this.getList()
				// this.selectComponent('#item').toggle();  
			},
			checkType(data) {
				return Array.isArray(data)
			},
			changeTab(index, id, name) {
				// this.onTab(id,name)
				// let act = this.act;
				// console.log(name, id);
				let status = false
				this.setData({
					[`screen_index[1]`]: index,
					[`tab_list[${1}].name`]: name == '全部' ? '工艺' : name,
					[`tab_list[${1}].act`]: id,
					// [`tab_list[${1}].show`]:status,
					// screen_popup:status
					list: [],
					markers: [],
					page: 1,
					highlightedIndex:0
				});
				this.getList()
				this.getIp(11,name)
				setTimeout(() => {
					this.closePopup()
				}, 50)
				console.log(id)
				// this.getList();
				// this.onClose();
			},
			getLocation() {
				const that = this

				return new Promise((resolve, reject) => {
					uni.getLocation({
						isHighAccuracy: true,
						type: 'gcj02',
						success(res) {
							resolve(res)
						},
						err(err) {
							reject(err)
						}
					})
				})
			},
			openSet() {
				uni.openSetting({
					success(res) {
						console.log(res)
					},
					fail() {}
				})
			},
			ontabSel(e, _dataset) {
				/* ---处理dataset begin--- */
				// this.handleDataset(e, _dataset);
				/* ---处理dataset end--- */
				let index = e.currentTarget.dataset.i;

				this.tab_list.forEach((item, i) => {
					item.act = (index === i) ? i : '';
					item.show = (index === i);
				});
				// let status = this.tab_list[i].show;
				// this.setData({
				// 	[`tab_list[0].show`]: false,
				// 	[`tab_list[1].show`]: false,
				// 	// [`tab_list[2].show`]: false,
				// 	[`tab_list[${i}].show`]: !status,
				// 	act: i
				// });
			},
			onRegion(e, _dataset) {
				/* ---处理dataset begin--- */
				// this.handleDataset(e, _dataset);
				/* ---处理dataset end--- */
				let name = e.currentTarget.dataset.name;
				let id = e.currentTarget.dataset.id;
				let type = e.currentTarget.dataset.type;
				this.setData({
					[`region[${type}].name`]: name,
					[`region[${type}].act`]: id
				});
				if (type == 0) {
					this.getArea(id);
				} else if (type == 1) {
					this.setData({
						page: 1,
						list: [],
						markers: [],
						[`tab_list[2].name`]: name === '全部' ? '地区' : name
					});
					setTimeout(() => {
						this.closePopup()
					}, 50)
					this.getList();
					this.getIp(11,name)
					this.latitude = this.my_latitude
					this.longitude = this.my_longitude
					this.highlightedIndex = 0;
				}
			},
			getInfo() {
				http.request('user/userInfo')
					.then((res) => {
						this.setData({
							cart_num: res.data.cart_count || 0
						});
					})
					.catch((res) => {
						uni.showToast({
							title: res.message,
							icon: 'none'
						});
					});
			},
			goSearch() {
				this.page = 1
				this.markers = []
				this.list = []
				this.getList()
				
				
				this.highlightedIndex = 0
				this.getIp(10,this.value)
				// uni.navigateTo({
				// 	url: '/pages/shopping/search'
				// });
			},
			getIp(type,name){
				http.request('demand/getIp',{
					type: type,
					id:0,
					text:name
				}).then(res=>{})
			},
			goFactoryMap(type) {
				let id=""
				if (type == 0) {
					id = this.detail.id
				}
				uni.navigateTo({
					url: `/subPack/factoryMap/factoryMap?latitude=${this.latitude}&longitude=${this.longitude}&my_latitude=${this.my_latitude}&my_longitude=${this.my_longitude}&id=${id}`
				})
			},
			goPage(path, id) {
				if (!path) return

				if (path === '/subPack/factoryMap/factoryMap') {
					uni.navigateTo({
						url: `${path}?latitude=${this.latitude}&longitude=${this.longitude}&my_latitude=${this.my_latitude}&my_longitude=${this.my_longitude}&id=${this.detail.id}`
					})
					return
				}
				uni.navigateTo({
					url: id ? `${path}?id=${id}` : path
				})
			},
			getAreas(latitude, longitude) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: "https://apis.map.qq.com/ws/geocoder/v1/?location=",
						data: {
							key: "XUDBZ-3OVAL-KWEPB-MXU6W-KW4XK-6WBHF",
							location: `${latitude},${longitude}`
						},
						success(res) {
							resolve(res)
						},
						fail(err) {
							reject(err)
						}
					})
				})
			},
			wxAuthLogin() {
				let that = this;
				uni.login({
					complete: (res) => {
						let data = {
							code: res.code
						};
						let h = {
							'content-type': 'application/x-www-form-urlencoded'
						};
						uni.request({
							url: http.appUrl + 'login/getLogin',
							data: data,
							method: 'POST',
							header: h,
							success: (res) => {
								uni.setStorageSync('token', res.data.data.token.token);
								uni.setStorageSync('is_login', res.data.code);
							},
							fail(res) {
								console.log(res);
							}
						});
					}
				});
			},
			checkAuth(){
				const that = this
				uni.getSetting({  
				    success(res) {  
						console.log(res)
				        that.isAuth_location = res.authSetting['scope.userLocation']  
				        const latitude = uni.getStorageSync('latitude')  
				        const longitude = uni.getStorageSync('longitude')
						
				        const requestSettledList = (lat, lng, addressComponent) => {  
							lat = Number(lat)
							lng = Number(lng)
				            http.request('user_settled/list', {  
				                page: 1,  
				                pageSize: 1,  
				                longitude: lng,  
				                latitude: lat,  
				                my_longitude: lng,  
				                my_latitude: lat,  
				                keyword: '',  
				                distance: 0,  
				                machining: 0,  
				                service_industry: 0,  
				                province:'',  
				                city:"",
								type:0
				            }).then(ress => {  
				                that.settled_list = ress.data.data
								that.settled_list.forEach(item=>{
									item.machining = item.machining.join('、')
									item.service_industry = item.service_industry.join('、')
									item.machining_products.forEach(el => {  
									    if (el.url.startsWith('[')) {  
									        try {  
									            el.url = JSON.parse(el.url);  
									        } catch (e) {  
									            el.url = null;
									        }  
									    }
									});
								})
								
				            }).catch(err => {  
				                uni.showToast({
									title:err.message,
									icon:'none'
								})
				            });  
				        }  
				
				        // 如果已授权，且有坐标信息  
				        if (that.isAuth_location && latitude && longitude && uni.getStorageSync('address_component')) {  
				            const address_component = JSON.parse(uni.getStorageSync('address_component'));  
				            requestSettledList(latitude, longitude, address_component);  
				            return; // 提早返回  
				        }  
						
				        // 获取用户位置  
				        uni.getLocation({  
				            isHighAccuracy: true,  
				            type: 'gcj02',  
				            success(rest) {  
				                const { latitude, longitude } = rest;  
				                that.my_longitude = longitude;  
				                that.my_latitude = latitude;  
				                uni.setStorageSync('latitude', latitude);  
				                uni.setStorageSync('longitude', longitude);  
				
				                // 如果地址组件已存在  
				                if (uni.getStorageSync('address_component')) {  
				                    const address_component = JSON.parse(uni.getStorageSync('address_component'));  
				                    requestSettledList(latitude, longitude, address_component);  
				                } else {  
				                    // 如果不存在，则请求地址组件  
				                    uni.request({  
				                        url: "https://apis.map.qq.com/ws/geocoder/v1/",  
				                        data: {  
				                            key: "XUDBZ-3OVAL-KWEPB-MXU6W-KW4XK-6WBHF",  
				                            location: `${latitude},${longitude}`  
				                        },
				                        async success(result) {  
				                            const data = result.data.result.address_component;  
				                            uni.setStorageSync('address_component', JSON.stringify(data));  
											that.isAuth_location=true
				                            await requestSettledList(latitude, longitude, data); 
											that.latitude = latitude
											that.longitude = longitude
											that.getList(longitude,latitude)
				                        },  
										
				                        fail(err) {  
				                            console.error('Error fetching address component:', err);  
				                        }  
				                    }); 
				                }
								
								 
				            },  
				            fail(err) {
								that.isAuth_location = false
				                console.error('Failed to get location:', err);  
				            }  
				        });  
				    }  
				});
				
			},
		}
	};
</script>
<style lang="scss">
	@import './shopping.css';

	.customCallout_active {

		&::after,
		&::before {
			border-color: #0F50C6 transparent transparent !important;
		}
	}

	@keyframes border {
		0% {
			opacity: 0;
		}

		100% {
			opacity: 1;
		}
	}

	.highlight-card {
		position: absolute;
		right: 0;
		top: 0;
		height: 70rpx;
		width: 100rpx;
		overflow: hidden;
		animation: border 0.3s;

		.highlight-box {
			position: absolute;
			width: 200rpx;
			height: 200rpx;
			background: #4874CB;
			transform: rotate(-45deg);
			transform-origin: center;
			top: -150%;
			left: 35px;
		}

		// ::after {
		// 	content: "";

		// }

		display:flex;
		align-items:center;
		justify-content: flex-end;

		image {
			width: 30rpx;
			z-index: 9;
			position: absolute;
			height: 30rpx;
			top: 10rpx;
			right: 4rpx;
		}
	}
</style>